package com.maserb.monitor.database;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DeviceDatabaseCreator {
    public void create(String jdbcDriver, String url, String username, String password, String dbname) {
        Connection conn = null;
        Statement stmt = null;
        DriverManagerDataSource dataSource = null;
        try {
            Class.forName(jdbcDriver);
            conn = DriverManager.getConnection(url, username, password);
            stmt = conn.createStatement();
            String sqlFormat = "CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARSET utf8 COLLATE utf8_general_ci";
            String sql = String.format(sqlFormat, dbname);
            stmt.executeUpdate(sql);

        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException se2) {
                try {
                    if (conn != null)
                        conn.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
            }
        }
    }
}
